package org.amse.korovkin.ciphering.view;

import java.awt.event.ActionEvent;
import java.io.*;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.amse.korovkin.ciphering.Main;

public class StatisticJDialog extends MyJDialog{
    public static final int CANCEL = MyJDialog.CLOSE;
    public static final int OPEN_MODE = 1;
    public static final int LOAD_MODE = 2;
    private boolean loadFlag = false;
    public StatisticJDialog(CipheringJFrame jFrame) {
        super(jFrame, "Statistic");
        jl.setText("StatisticFile");
        action.setAction(new LoadStandartStatisticAction(this));
        setVisible(true);
    }

    @Override
    public void pressOk() {
        if (tf.getText().length() != 0) {
            parent.setStatisticPath(tf.getText());
            if (loadFlag) {
                returnValue = LOAD_MODE;
            } else {
                returnValue = OPEN_MODE;
            }
            this.dispose();
        } else {
            JOptionPane.showMessageDialog(this, "Please choose StatisticFile", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    public void setLoadFlag(boolean flag) {
        loadFlag = flag;
    }
    public static class LoadStandartStatisticAction extends AbstractAction {
        StatisticJDialog parent;
        public LoadStandartStatisticAction(StatisticJDialog jFrame) {
            parent = jFrame;
            putValue(SHORT_DESCRIPTION, "Load standart statistic");
            ClassLoader cl = Main.class.getClassLoader();
            putValue(LARGE_ICON_KEY, new ImageIcon(cl.getResource(MyJDialogActions.OPEN_SMALL_ICON_PATH)));
        }
        public void actionPerformed(ActionEvent e) {
            JFileChooser fch;
            try {
                fch = new JFileChooser(MainJFrameActions.loadLastFilePath());
                FileNameExtensionFilter filter = new FileNameExtensionFilter("Statistic files", "dat");
                fch.setFileFilter(filter);
            } catch (IOException ex) {
                ex.printStackTrace();
                fch = new JFileChooser(".");
            }
            int returnVal = fch.showOpenDialog(fch);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                parent.setFilePath(fch.getSelectedFile().getPath());
                try {
                    MainJFrameActions.saveLastFilePath(fch.getSelectedFile().getPath());
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            parent.setLoadFlag(true);
        }
    }

}
